package com.example.demo.config;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.zaxxer.hikari.HikariDataSource;

import io.shardingjdbc.core.api.ShardingDataSourceFactory;
import io.shardingjdbc.core.api.config.ShardingRuleConfiguration;
import io.shardingjdbc.core.api.config.TableRuleConfiguration;
import io.shardingjdbc.core.api.config.strategy.StandardShardingStrategyConfiguration;

@Configuration
@EnableConfigurationProperties
public class ShardingConfig {

	@Bean
	public DataSource shardingDatasoucre() throws SQLException {
		Properties properties = new Properties();
		properties.setProperty("sql.show", "true");
		TableRuleConfiguration tableRuleConfiguration = new TableRuleConfiguration();
		tableRuleConfiguration.setLogicTable("t_test");
		tableRuleConfiguration.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("create_time",
				DateAlgorithm.class.getName(), RangeTable.class.getName()));
		ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
		shardingRuleConfiguration.getTableRuleConfigs().add(tableRuleConfiguration);
		DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap(), shardingRuleConfiguration,
				new HashMap<>(), properties);
		return dataSource;
	}


	@Autowired
	DataSourceProperties dataSourceProperties;

	Map<String, DataSource> dataSourceMap() {
		DataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
		Map<String, DataSource> dataSourceMap = new HashMap<>(2);
		dataSourceMap.put("master", dataSource);
		return dataSourceMap;
	}

}
